package com.changcheng.service.Imp;
import com.changcheng.mapper.RecordMapper;
import com.changcheng.pojo.Record;
import com.changcheng.pojo.Do.RecordInDo;
import com.changcheng.service.RecordService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
public class RecordServiceImp implements RecordService {
    @Autowired
    private RecordMapper recordMapper;

    @Override
    public List<Record> findAllRecord(int offset, int limit) {
        List<Record> list;
        PageHelper.startPage(offset, limit);
        list = recordMapper.findAllRecord();
        return list;
    }

    @Override
    public void addRecord(int userid, String username, String operation_name, String operation_result) {
        RecordInDo recordInDo = new RecordInDo();
        Date operation_time = new Date();
        recordInDo.setUser_id(userid);
        recordInDo.setUser_name(username);
        recordInDo.setOperation_name(operation_name);
        recordInDo.setOperation_time(operation_time);
        recordInDo.setOperation_result(operation_result);
        recordMapper.addRecord(recordInDo);
    }

    private DateFormat dateFormatSimple = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public List<Record> findRecord(Integer userID, String startDateStr, String endDateStr, int offset, int limit) {
        Date startDate=null;
        Date endDate=null;
        try {
            if (StringUtils.isNotEmpty(startDateStr)) {
                 startDate = dateFormatSimple.parse(startDateStr);
            }
            if (StringUtils.isNotEmpty(endDateStr)) {
                 endDate = dateFormatSimple.parse(endDateStr);
                endDate = DateUtils.addDays(endDate, 1);
            }
        } catch (ParseException e) {
            throw new RuntimeException("日期格式化出错");
        }
        PageHelper.startPage(offset,limit);
        return recordMapper.findRecord(userID,startDate,endDate);

    }
}
